package edu.pitt.cs3530.scripts;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class SplitEnergy {
	public static void main(String args[]) {
		File file = new File(args[0]);
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			ArrayList<Double> list = new ArrayList<Double>();
			int i = 0;
			boolean inSection = true;
			double currentWattage = 0;
			double lastWattage = 0;
			while (reader.ready()) {
				String line = reader.readLine();
				if ((line != null) && (line.trim().length() > 0)) {
					StringTokenizer tok = new StringTokenizer(line, ",\t ");
					String token = tok.nextToken();
					if (!token.equalsIgnoreCase("Time")) {
						currentWattage = Double.parseDouble(tok.nextToken());
						if (inSection && (currentWattage < 100)) {
							inSection = !inSection;
							i++;
							writeTrace(list, file.getParent() + "/" + i);
							list.clear();
						} else if (!inSection && (currentWattage > 100)) {
							inSection = !inSection;
						}
						if (inSection) {
							list.add(currentWattage);
						}
					}
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void writeTrace(List<Double> doubles, String fileName) {
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
			for (Double d : doubles) {
				writer.write("" + d + "\r\n");
			}
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
